package com.example.administrator.myapplication.net.chain;

import android.util.Log;

import com.example.administrator.myapplication.net.HttpCodec;
import com.example.administrator.myapplication.net.HttpConnection;
import com.example.administrator.myapplication.net.Response;

import java.io.InputStream;
import java.util.HashMap;

public class CallServerInterceptor implements Interceptor {
    private String tag = "CallServerInterceptor";

    @Override
    public Response intercept(InterceptorChain chain) throws Exception {
        Log.e(tag, "通信拦截器");
        HttpConnection connection = chain.connection;
        HttpCodec codec = new HttpCodec();
        InputStream is = connection.call(codec);
        String statusLine = codec.readLine(is);
        HashMap<String, String> headers = codec.readHeaders(is);
        int contentLength = -1;
        if (headers.containsKey("Content-Length")) {
            contentLength = Integer.parseInt(headers.get("Content-Length")) ;
        }
        boolean isChunked = false;
        if (headers.containsKey("Transfer-Encoding")) {
            isChunked = headers.get("Transfer-Encoding").equals(HttpCodec.HEAD_VALUE_CHUNKED);
        }

        String body = null;
        if (contentLength > 0) {
            byte[] bytes = codec.readBytes(is, contentLength);
            body = new String(bytes);
        } else if (isChunked) {
            body = codec.readChunked(is);
        }
        boolean isKeepAlive = false;
        String[] status = statusLine.split(" ");
        if (headers.containsKey(HttpCodec.HEAD_CONNECTION)){
            isKeepAlive = headers.get(HttpCodec.HEAD_CONNECTION).equals("keep-alive");
        }
        connection.setLastUseTime(System.currentTimeMillis());
        return new Response(status[1],contentLength,headers,body,isKeepAlive);
    }
}
